<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search as IconSearch } from '@element-plus/icons-vue'
import userApi from '@/api/user'

interface UserInfo {
  userId: number
  username: string
  realName: string
  phone: string
  email: string
  role: string
  status: boolean
  createdAt: string
  updatedAt: string
}

const userRole = ref('')
const tableData = ref<UserInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchUsername = ref('')
const searchStatus = ref(true)

// 获取用户角色
onMounted(() => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    const user = JSON.parse(userInfo)
    userRole.value = user.role === 'admin' ? '管理员' : user.role === 'manager' ? '经理' : '操作员'
  }
})

// 获取用户列表
const getUserList = async () => {
  try {
    const res = await userApi.getUserList({
      page: currentPage.value,
      pageSize: pageSize.value,
      username: searchUsername.value,
      status: searchStatus.value
    })
    if (res.data) {
      tableData.value = res.data.list
      total.value = res.data.total
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.warning(res.message || '未获取到用户数据')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    tableData.value = []
    total.value = 0
  }
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getUserList()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getUserList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

// 处理删除用户
const handleDelete = async (userId: number) => {
  try {
    await userApi.deleteUser(userId)
    ElMessage.success('删除用户成功')
    getUserList()
  } catch (error) {
    ElMessage.error('删除用户失败')
  }
}

// 初始化加载数据
onMounted(() => {
  getUserList()
})
</script>

<template>
  <div class="user-list-container">
    <div class="search-bar">
      <el-input
        v-model="searchUsername"
        placeholder="请输入用户名搜索"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><icon-search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="searchStatus" class="search-select" @change="handleSearch">
        <el-option :value="true" label="启用" />
        <el-option :value="false" label="禁用" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="realName" label="真实姓名" width="120" />
      <el-table-column prop="phone" label="手机号" width="120" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="role" label="角色" width="100">
        <template #default="{ row }">
          {{ row.role === 'admin' ? '管理员' : row.role === 'manager' ? '经理' : '操作员' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="{ row }">
          <el-button
            v-if="userRole === '管理员'"
            type="danger"
            size="small"
            @click="handleDelete(row.userId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.search-select {
  width: 120px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>